package com.tarry.threadpool;

import java.util.concurrent.*;

public class ThreadPoolMain {

    public static void main(String[] args) {
        CacheData cacheData = new CacheData();
        ThreadLocalRandom random = ThreadLocalRandom.current();
        int cpus = Runtime.getRuntime().availableProcessors();
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                cpus,
                cpus * 2,
                10L,
                TimeUnit.SECONDS,
                // 双锁线程安全的队列，有界，最大长度为Integer.MAX_VALUE
                new LinkedBlockingQueue<>(2000),
                // 自定义拒绝策略
                (r, e) -> {
                    if (!e.isShutdown()) {
                        try {
                            // put 队列满时，阻塞队列
                            e.getQueue().put(r);
                        } catch (InterruptedException ex) {
                            throw new RuntimeException(ex);
                        }
                    }
                }
        );

        while (true) {

            // 读数据
            poolExecutor.submit(cacheData::getNumber);

            // 写数据
            poolExecutor.submit(() -> cacheData.setNumber(random.nextInt(Integer.MAX_VALUE)));
        }
    }
}
